#include <iostream>
#include <set>
#include <cmath>
using namespace std;

const int N = 1e6 + 10;
const int INF = 1e7 + 10;

multiset<int> sl;
int misl;

int main(){
	int n;
	cin >> n;
	cin >> misl;
	sl.insert(misl);
	sl.insert(-INF); sl.insert(INF);
	while(--n){
		int x;
		cin >> x;
		auto lb = sl.lower_bound(x);
		auto tmp = lb;
		tmp--; 
		if(*lb == x) continue;
		
		misl += min(abs(*lb - x),abs(*tmp - x));
		
		sl.insert(x);
	}
	cout << misl << endl;
	return 0;
} 
